<template>
  <el-card class="card">
    <div class="t_box bottom">
      <div class="s_box">
        <el-input class="s_item" placeholder="请输入资产编号..." v-model="queryForm.map.zcbh" clearable @clear="reset"></el-input>
        <el-input class="s_item" placeholder="请输入资产名称..." v-model="queryForm.map.zcmc" clearable @clear="reset"></el-input>
        <el-select
                class="s_item"
                placeholder="资产类别"
                style="width: 130px"
                v-model="queryForm.map.typeId"
        >
          <el-option
                  v-for="(item,index) in assetTypeData"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
          />
        </el-select>
        <el-button type="primary" :icon="Search" @click="initAssetDepList">搜索</el-button>
        <el-button type="info" :icon="Setting" @click="reset">重置</el-button>
      </div>
      <div>
        <el-button type="danger" :icon="Edit" @click="handleDepDialog">折旧处理</el-button>
        <el-button type="success" :icon="SoldOut" @click="exportExcel">导出文件</el-button>
      </div>
    </div>
    <el-table
            ref="tableDataRef"
            :data="tableData"
            border stripe
            :cell-style="{textAlign: 'center',background:'#fff'}"
            :header-cell-style="{textAlign: 'center'}"
            @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="zjsj" label="折旧时间" width="130" fixed :formatter="formatDate"/>
      <el-table-column prop="zcbh" label="资产编号" width="130" fixed/>
      <el-table-column prop="zcmc" label="资产名称" width="130"/>
      <el-table-column label="资产类别" width="150" :formatter="formatAssetType"/>
      <el-table-column prop="zjff" label="折旧方法" width="120"/>
      <el-table-column prop="zjnx" label="折旧年限" width="90"/>
      <el-table-column prop="yuanzhi" label="原值" width="80"/>
      <el-table-column prop="jingzhi" label="净值" width="80"/>
      <el-table-column prop="canzhi" label="残值" width="80"/>
      <el-table-column prop="canzhilv" label="残值率" width="80"/>
      <el-table-column prop="rksj" label="入库时间" width="130" :formatter="formatDate"/>
      <el-table-column prop="zjje" label="折旧金额"/>
    </el-table>
    <el-pagination
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10,20,20,40,50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
  </el-card>
  <Dialog
          v-model="depDialogVisible"
          :dialog-visible="depDialogVisible"
          :dialog-title="depDialogTitle"
          @initAssetDepList="initAssetDepList"
  />
</template>

<script setup>
import { ref } from "vue";
import request from "@/util/request";
import moment from "moment";
import { Delete, Edit, Search, SoldOut, Setting } from '@element-plus/icons-vue';
import Dialog from "./components/dialog";
import XLSX from "xlsx";
import { ElMessage, ElMessageBox } from "element-plus";

/**
 * 表格数据
 */
const tableData = ref([]);

/**
 * 数据总数
 */
const total = ref(0);

/**
 * 查询条件
 */
const queryForm = ref({
  map: {
    zcmc: "",
    zcbh: "",
    typeId: "",
  },
  pageNum: 1,
  pageSize: 10
})

/**
 * 获得折旧数据
 */
const initAssetDepList = async () => {
  const res = await request.post("assetDepreciation/list", queryForm.value);
  console.log(res.data.assetDepreciationList)
  tableData.value = res.data.assetDepreciationList;
  total.value = res.data.total;
}
initAssetDepList();

/**
 * 处理每页记录数变化
 */
const handleSizeChange = (pageSize) => {
  queryForm.value.pageNum = 1;
  queryForm.value.pageSize = pageSize;
  initAssetDepList();
}

/**
 * 处理第几页变化
 */
const handleCurrentChange = (pageNum) => {
  queryForm.value.pageNum = pageNum;
  initAssetDepList();
}

/**
 * 格式化资产类别assetType数组信息
 */
const formatAssetType = (row) => {
  return row.assetType.name
}

// const formatAssetType = (val) => {
//   return row.assetsType.name
// }

const formatShsj = (row) => {
  return row.shsj != null ? row.shsj : <el-tag type="success" effect="dark">未损坏</el-tag>;
}

/**
 * 表格通用格式化时间信息
 */
const formatDate = (row, column) => {
  let date = row[column.property];
  if (date === undefined) {
    return "";
  }
  return moment(date).format("YYYY-MM-DD");
}

/**
 * 通用格式化时间信息
 */
const currencyFormatDate = (data) => {
  let date = data;
  if (date === undefined) {
    return "";
  }
  return moment(date).format("YYYY-MM-DD");
}

const assetTypeData = ref([])

const initAssetTypeList = async () => {
  const res = await request.get("assetType/list");
  assetTypeData.value = res.data.assetTypeList;
}
initAssetTypeList();

/**
 * 重置
 */
const reset = () => {
  queryForm.value.map.zcmc = "";
  queryForm.value.map.zcmc = "";
  queryForm.value.map.typeId = "";
  initAssetDepList();
}

/**
 * 折旧处理框是否打开标识
 */
const depDialogVisible = ref(false);

/**
 * 折旧处理框标题
 */
const depDialogTitle = ref("");

/**
 * 打开折旧处理框方法
 */
const handleDepDialog = () => {
  depDialogVisible.value = true;
  depDialogTitle.value = "资产设备折旧处理";
}

const ids = ref([]) //表格选中数据的id集合

/**
 * 表格选中方法
 */
const handleSelectionChange = (selection) => {
  if (selection.length >= 1) {
    ids.value = selection;
  } else {
    ids.value = [];
  }
}

/**
 * 表格数据导出Excel实际方法
 * @param list
 */
const exportList = (list) => {
  //表格表头,导出表头
  let tableHeader = [[
    '折旧时间', '资产编号', '资产名称',
    '资产类别', "折旧方法", "折旧年限",
    "原值", "净值", "残值", "残值率",
    "入库时间", "折旧金额"
  ]]
  //参数遍历添加内容
  list.forEach((item, index) => {
    let rowData = []
    //导出内容的字段
    rowData = [
      currencyFormatDate(item.zjsj),
      item.zcbh,
      item.zcmc,
      item.assetType.name,
      item.zjff,
      item.zjnx,
      item.yuanzhi,
      item.jingzhi,
      item.canzhi,
      item.canzhilv,
      currencyFormatDate(item.rksj),
      item.zjje,
    ]
    tableHeader.push(rowData)
  })
  //创建excel文件
  let ws = XLSX.utils.aoa_to_sheet(tableHeader)
  let wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '资产设备折旧表') //工作簿名称
  XLSX.writeFile(wb, '资产设备折旧信息.xlsx') //保存的文件名
}

//导出
const exportVariable = ref({
  title: "确认导出全部数据吗",
  idArray: [],
  dataList: [],
})

//重置excel基本变量
const resetExportVariable = () => {
  exportVariable.value.title = "确认导出全部的数据吗";
  exportVariable.value.idArray = [];
  exportVariable.value.dataList = [];
}

/**
 * 表格数据导出Excel调用方法
 */
const exportExcel = async () => {
  //首先判断导出全部数据还是导出选中的数据
  //如果定义选中数据的id数组不为空执行如下的if语句重新赋值
  if (ids.value.length !== 0) {
    ids.value.forEach((item) => {
      exportVariable.value.idArray.push(item.id)
    })
    console.log(exportVariable.value.idArray)
    //改变提示信息
    exportVariable.value.title = "确认导出选中的数据吗"
    //根据id数组查询数据
    const res = await request.post("assetDepreciation/listById", exportVariable.value.idArray);
    //赋值给传参数组
    exportVariable.value.dataList = res.data.assetDepList;
  }
  ElMessageBox.confirm(
          exportVariable.value.title,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(async () => {
            //判断传参数组是否为空
            if (exportVariable.value.dataList.length === 0) {
              //为空导出全部数据
              const res = await request.get("assetDepreciation/listAll");
              console.log(res.data.assetDepAllList)
              exportList(res.data.assetDepAllList);
            } else {
              //不为空导出选中的数据
              exportList(exportVariable.value.dataList);
              resetExportVariable();
            }
            ElMessage.success("导出成功")
          })
          .catch(() => {
            //消息提示框点击取消或者关闭重置导出excel基本变量
            resetExportVariable();
          })
}
</script>

<style lang="scss" scoped>
.card {
  border: none;
  border-radius: 0;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

::v-deep th.el-table__cell {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 15px;
}

.t_box {
  display: flex;
  justify-content: space-between;
}

.s_box {
  display: flex;
  width: 50%;
}

.bottom {
  margin-bottom: 15px;
}

.s_item {
  flex: 1;
  margin-right: 15px;
}
</style>